package com.ruoyi.teaching.controller;

import java.util.List;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.teaching.bo.HighInterviewMasteryListBo;
import com.ruoyi.teaching.bo.QueryInterviewMasterBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.teaching.domain.YaHighInterview;
import com.ruoyi.teaching.service.IYaHighInterviewService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * 高频面试题Controller
 * 
 * @author ruoyi
 * @date 2025-03-14
 */
@RestController
@RequestMapping("/interview")
@Slf4j
public class YaHighInterviewController extends BaseController
{
    @Autowired
    private IYaHighInterviewService yaHighInterviewService;

    // 存储所有SSE连接，，这些都是由多个客户端时才会用到
    private final Map<String, SseEmitter> sseEmitters = new ConcurrentHashMap<>();

    // 定时任务执行器
    private final ScheduledExecutorService scheduledExecutor = new ScheduledThreadPoolExecutor(1);

    /**
     * 创建SSE连接，用于实时获取导出进度
     */
    @GetMapping(value = "/export/es/progress/sse", produces = "text/event-stream;charset=UTF-8")
    public SseEmitter exportEsProgressSSE() {
        // 创建SSE连接，超时时间设置为30分钟
        String clientId = "client_" + System.currentTimeMillis();
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);

        // 注册回调，这些都是由多个客户端时才会用到
        emitter.onCompletion(() -> sseEmitters.remove(clientId));
        emitter.onTimeout(() -> sseEmitters.remove(clientId));
        emitter.onError(e -> sseEmitters.remove(clientId));

        // 存储连接，这些都是由多个客户端时才会用到
        sseEmitters.put(clientId, emitter);

        // 立即发送一次进度
        try {
            emitter.send(SseEmitter.event()
                    .name("progress")
                    .data(yaHighInterviewService.queryExportEsProgress()));
        } catch (IOException e) {
            log.error("发送SSE消息失败", e);
            emitter.completeWithError(e);
            return emitter;
        }

        // 启动定时任务，每秒发送一次进度
        scheduledExecutor.scheduleAtFixedRate(() -> {
            try {
                Integer progress = yaHighInterviewService.queryExportEsProgress();
                emitter.send(SseEmitter.event()
                        .name("progress")
                        .data(progress));

                // 如果进度达到100%，完成连接
                if (progress >= 100) {
                    emitter.complete();
                    sseEmitters.remove(clientId);
                }
            } catch (IOException e) {
                log.error("发送SSE消息失败", e);
                emitter.completeWithError(e);
                sseEmitters.remove(clientId);
            }
        }, 1, 1, TimeUnit.SECONDS);

        return emitter;
    }
    /**
     * 查询进度条进度（未实现的低配版，没用到see）
     */
    @RequiresPermissions("teaching:interview:query")
    @GetMapping(value = "/export/es/percentage")
    public AjaxResult progress()
    {
        return success(yaHighInterviewService.queryExportEsProgress());
    }
    /**
     * flink批量导出高频面试题列表（从mysql到ES的数据全量同步）
     */
    @RequiresPermissions("teaching:interview:export")
    @Log(title = "高频面试题", businessType = BusinessType.EXPORT)
    @PutMapping("/exportEs")
    public AjaxResult exportEs()
    {
        yaHighInterviewService.exportEs();
        return AjaxResult.success();
    }

    /**
     * 根据关键字查询关联面试题
     */
    @RequiresPermissions("teaching:interview:list")
    @PostMapping("/queryRelatedInterviewByKeywords")
    public AjaxResult queryRelatedInterviewByKeywords(@RequestBody List<String> keywords)
    {
        return success(yaHighInterviewService.queryRelatedInterviewByKeywords(keywords));
    }
    /**
     * 查询关联面试题
     */
    @RequiresPermissions("teaching:interview:list")
    @GetMapping("/queryRelatedInterview")
    public AjaxResult queryRelatedInterview(@RequestParam("courseContext") String courseContext,
                                            @RequestParam("id") Long id)
    {
        return success(yaHighInterviewService.queryRelatedInterview(id,courseContext));
    }

    /**
     * 查询高频面试题列表(附带掌握情况)
     */
    @RequiresPermissions("teaching:interview:list")
    @GetMapping("/list/mastery_degree")
    public TableDataInfo list(QueryInterviewMasterBo queryInterviewMasterBo)
    {
        startPage();
        List<HighInterviewMasteryListBo> list = yaHighInterviewService.selectYaInterviewMasteryList(queryInterviewMasterBo);
        return getDataTable(list);
    }

    /**
     * 查询高频面试题列表
     */
    @RequiresPermissions("teaching:interview:list")
    @GetMapping("/list")
    public TableDataInfo list(YaHighInterview yaHighInterview)
    {
        startPage();
        List<YaHighInterview> list = yaHighInterviewService.selectYaHighInterviewList(yaHighInterview);
        return getDataTable(list);
    }

    /**
     * 导出高频面试题列表
     */
    @RequiresPermissions("teaching:interview:export")
    @Log(title = "高频面试题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YaHighInterview yaHighInterview)
    {
        List<YaHighInterview> list = yaHighInterviewService.selectYaHighInterviewList(yaHighInterview);
        ExcelUtil<YaHighInterview> util = new ExcelUtil<YaHighInterview>(YaHighInterview.class);
        util.exportExcel(response, list, "高频面试题数据");
    }

    /**
     * 获取高频面试题详细信息
     */
    @RequiresPermissions("teaching:interview:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yaHighInterviewService.selectYaHighInterviewById(id));
    }

    /**
     * 新增高频面试题
     */
    @RequiresPermissions("teaching:interview:add")
    @Log(title = "高频面试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YaHighInterview yaHighInterview)
    {
        return toAjax(yaHighInterviewService.insertYaHighInterview(yaHighInterview));
    }

    /**
     * 修改高频面试题
     */
    @RequiresPermissions("teaching:interview:edit")
    @Log(title = "高频面试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YaHighInterview yaHighInterview)
    {
        return toAjax(yaHighInterviewService.updateYaHighInterview(yaHighInterview));
    }

    /**
     * 删除高频面试题
     */
    @RequiresPermissions("teaching:interview:remove")
    @Log(title = "高频面试题", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yaHighInterviewService.deleteYaHighInterviewByIds(ids));
    }
}
